from rest_framework import serializers

from complains.models import Complain, Comment
from users.models import User


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ["id", "username"]


class ComplainListSerializer(serializers.ModelSerializer):
    """吐槽列表序列化器"""

    class Meta:
        model = Complain
        fields = ["id", "user_id", "like_count", "create_time", "content",  ]


class ComplainCommentSerializer(serializers.ModelSerializer):
    """
    评论模型类序列化器
    """
    user_id = serializers.StringRelatedField(label="用户名")

    class Meta:
        model = Comment
        fields = ["id", "complain_id", "user_id", "content",
                  "comment_like_count"]

    def validate_content(self, value):
        if value is None:
            return serializers.ValidationError("评论内容不能为空")
        return value

    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class ComplainDetailSerializer(serializers.ModelSerializer):
    """
    吐槽详情序列化器
    """
    user_id = UserSerializer
    comment = ComplainCommentSerializer(many=True)

    class Meta:
        model = Complain
        fields = ('id', 'content', 'like_count', 'comment_count', 'user_id', 'comment',)
        depth = 1


class SendComplainSerializer(serializers.ModelSerializer):
    class Meta:
        model = Complain
        fields = ('content', 'user_id')

        # def validate(self, attrs):
        #     try:
        #         user = self.context['request'].user
        #     except Exception:
        #         raise serializers.ValidationError("用户不存在")
        #     attrs['user'] = user
        #     return attrs


class ComplainLikeserizlizer(serializers.ModelSerializer):
    class Meta:
        model = Complain
        fields = ['id', 'content', 'user_id']

        def validate(self, attrs):
            try:
                user_id = self.context['request'].user_id
            except Exception:
                raise serializers.ValidationError("用户不存在")
            attrs['user_id'] = user_id
            return attrs
